package com.example.restful01.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.restful01.mapper.BookMapper;
import com.example.restful01.model.Book;
import com.example.restful01.repository.BookRepository;
import com.example.restful01.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Autowired
    BookMapper bookMapper;
    @Autowired
    private BookRepository bookRepository; // 注入 BookRepository

    @Override
    public List<Book> searchBook(String name) {
        return bookMapper.searchBook(name);
    }

    @Override
    public boolean changeBookInfo(Book book) {
        return bookMapper.changeBookInfo(book)>0;
    }


    // 通用方法用于更新书籍信息
    public Book updateBookInfo(Integer id, String field, String value) {
        // 根据 ID 查找书籍，如果不存在则抛出异常
        Book book = bookRepository.findById(id).orElseThrow(() -> new RuntimeException("Book not found"));

        // 根据字段名更新书籍信息
        switch (field) {
            case "bookName":
                book.setBookName(value); // 更新书名
                break;
            case "author":
                book.setAuthor(value); // 更新作者
                break;
            case "position":
                book.setPosition(value); // 更新位置
                break;
            case "amount":
                book.setAmount(value); // 更新数量
                break;
            // 如果需要，可以添加更多字段的更新逻辑
            default:
                throw new RuntimeException("Invalid field"); // 无效字段异常
        }

        // 保存更新后的书籍信息
        return bookRepository.save(book);
    }
}
